﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace ToDoWebRole
{
    //Azure Table Storage source
    public class ToDoDataSource
    {
        private ToDoDataServiceContext context = null;

        //Connect to storage. Create context. Lazy initialize table.
        public ToDoDataSource()
        {
            //Connect to storage
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
 configSetter(ConfigurationManager.AppSettings[configName]));
            var sa = CloudStorageAccount.FromConfigurationSetting("AzureConnectionString");

            //Create context
            context = new ToDoDataServiceContext(sa.TableEndpoint.ToString(), sa.Credentials);

            //Ensure that table exists
            var cloudClient = sa.CreateCloudTableClient();
            if (cloudClient.DoesTableExist(ToDoDataServiceContext.ToDoTableName) == false)
            {
                //Strictly speaking, this is a race condition -- table could come into existence from other source while this block executes. We can ignore it for our purposes. 
                cloudClient.CreateTableIfNotExist(ToDoDataServiceContext.ToDoTableName);

            }

            //Ensure that the _ROOT task exists. Ditto race condition possibility, ditto ignore.
            if (!context.ToDoTable.ToList<ToDoDataModel>().Any(t => t.ID == ToDoDataModel.ROOT_ID))
            {
                var root = new ToDoDataModel(ToDoDataModel.ROOT_ID, String.Empty);
                root.ID = ToDoDataModel.ROOT_ID;
                root.IsComplete = false;
                root.DisplayName = "(Tasks)";
                Insert(root);
            }
        }

        //Generic "Select"
        public IEnumerable<ToDoDataModel> Select()
        {
            var rs = from todo in context.ToDoTable select todo;
            var query = rs.AsTableServiceQuery<ToDoDataModel>();
            return query.Execute();
        }

        private void Insert(ToDoDataModel todo)
        {
            context.AddObject(ToDoDataServiceContext.ToDoTableName, todo);
            context.SaveChanges();
        }
    }
}
